package com.cooper.scraper;

import com.cooper.scraper.ThreadPoolDownloadPublishRunner.ResultPool;
import com.cooper.scraper.ThreadPoolDownloadPublishRunner.RunnerThread;

import android.util.Log;

public abstract class ScraperRunnerThread extends RunnerThread {

	private boolean retryForScraperException = false;
	protected String key;
	protected String scraperId;
	
	public ScraperRunnerThread(ResultPool resultPool, String key, String scraperId) {
		super(resultPool);
		this.key = key;
		this.scraperId = scraperId;
	}

	@Override
	public final void run() {
		super.run();
		try {
			complete(key, runScraper());
		} catch (DownloadException e) {
			Log.e("ScraperRunnerThread", e.getMessage(), e);
			fail(key, e.getErrorCode());			
		} catch (ScraperException e) {
			Log.e("ScraperRunnerThread", e.getMessage(), e);
			if (!retryForScraperException) {
				retryForScraperException = true;
				ScraperManager.getInstance().cleanLocalScraper(scraperId);
				onCleanScraper();
				run();
			} else {
				fail(key, e.getErrorCode());
			}
		} catch (Exception e) {
			Log.e("ScraperRunnerThread", e.getMessage(), e);
			fail(key, DownloadException.ERROR_OTHER);
		}
	}

	protected abstract Object runScraper() throws DownloadException,
			ScraperException;
	
	protected void onCleanScraper(){
	}

}
